package com.wise.site.model;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.wise.site.R;
import com.wise.site.utils.Constanct;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

public class GoogleMapActivity extends MapActivity implements View.OnClickListener, LocationListener {
	
	private MapView mapView;
	private MapController mapController;
	private GeoPoint startPoint;
	private GeoPoint endPoint;
	private static final int LOADINGSUCCESS = 1000;
	private static final int LOADINGFAILE = LOADINGSUCCESS + 1;
	private LocationManager mLocationManager;
	//private MyLocationListener mLocationListener = new MyLocationListener();
	private Bitmap startBitmap;
	private Bitmap endBitmap;
	private String bestProvider;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.google_map_layout);
		
		findViewById(R.id.title_back).setOnClickListener(this);
		findViewById(R.id.search_path).setOnClickListener(this);
		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		startBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dest_mark);
		endBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.src_mark);
		mapView = (MapView)findViewById(R.id.mapView); 
		mapView.setBuiltInZoomControls(true);
		mapView.setTraffic(true);
		mapView.setSatellite(false); 
		mapView.setStreetView(true);
		mapController = mapView.getController();
		mapController.setZoom(14);
		mapController = mapView.getController(); 
		Toast.makeText(this, "正在加载地图", Toast.LENGTH_SHORT).show();
		new Thread(){
			public void run() {
				JSONObject jsonObject = getLocationInfo(getIntent().getStringExtra(Constanct.INTENT_ADDR));
				if(jsonObject != null){
					mHandler.sendMessage(mHandler.obtainMessage(LOADINGSUCCESS, jsonObject));
				}else{
					mHandler.sendEmptyMessage(LOADINGFAILE);
				}
			};
		}.start();
		bestProvider = mLocationManager.getBestProvider(getCriteria(), true);   //设置查询条件  
		//Location loc = mLocationManager.getLastKnownLocation("network");      //获取用户位置信息
		Location loc = mLocationManager.getLastKnownLocation(bestProvider);
		if(loc != null){
			mapView.getOverlays().clear();
			endPoint = new GeoPoint((int)(loc.getLatitude()*1E6), (int)(loc.getLongitude()*1E6));
			bindAddress(endPoint, endBitmap);
			if(startPoint != null){
				bindAddress(startPoint, startBitmap);
			}
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private JSONObject getLocationInfo(String addr){
		StringBuilder sb = new StringBuilder();
		JSONObject jsonObject = null;// = new JSONObject();
		addr = addr.replaceAll(" ", "%20");
		try {
			HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + addr + "&sensor=false");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response = client.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				sb.append((char) b);
			}
			jsonObject = new JSONObject(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}
	
	private GeoPoint getLatLong(JSONObject jsonObject){
		Double lon = new Double(0);
		Double lat = new Double(0);
		try {
			lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
			lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
	}
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			int what = msg.what;
			switch(what){
			case LOADINGSUCCESS:
				//mapController.setCenter(getLatLong((JSONObject)msg.obj));
				mapView.getOverlays().clear();
				startPoint = getLatLong((JSONObject)msg.obj);
				bindAddress(startPoint, startBitmap);
				mapController.setCenter(startPoint);
				if(endPoint != null){
					bindAddress(endPoint, endBitmap);
				}
				
				break;
			case LOADINGFAILE:
				Toast.makeText(GoogleMapActivity.this, "定位失败", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	
	private void bindAddress(GeoPoint point, Bitmap bitmap){
		//mapController.animateTo(point);
		List<Overlay> list = mapView.getOverlays();
		list.add(new MyPostionOverlay(bitmap, point));
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mLocationManager.requestLocationUpdates(bestProvider, 60000, 10, this);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mLocationManager.removeUpdates(this);
	}
	
	@Override
	public void onLocationChanged(Location location) {
		if(location != null){
			endPoint = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));
			mapView.getOverlays().clear();
			bindAddress(endPoint, endBitmap);
			if(startPoint != null){
				bindAddress(startPoint, startBitmap);
			}
		}
	}
	
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch(id){
		case R.id.title_back:
			finish();
			break;
		case R.id.search_path:
			showDialog();
			break;
		}
	}
	
	private void showDialog(){
		
		if(endPoint == null){
			Toast.makeText(this, "正在获取到您所在的位置，请稍候……", Toast.LENGTH_SHORT).show();
			return;
		}
		
		if(startPoint == null || endPoint == null){
			Toast.makeText(this, "缺少起点或终点", Toast.LENGTH_SHORT).show();
			return;
		}
		Resources resources = getResources();
		final CharSequence[] items = {resources.getString(R.string.bus), resources.getString(R.string.walk), resources.getString(R.string.driving)}; 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_access); 
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) { 
                StringBuilder params = new StringBuilder().append("&dirflg="); 
                switch (item) {
                case 0: 
                    params.append("r"); 
                    break; 
                case 1: 
                    params.append("w"); 
                    break; 
                case 2: 
                    params.append("d"); 
                    break; 
                default: 
                    break; 
                }
                getMap(params.toString());
            } 
        }); 

        AlertDialog alert = builder.create(); 
        alert.show();
	}
	
	private void getMap(String params) {
		try {
			String path = "http://ditu.google.cn/maps?f=d&source=s_d&saddr=" 
					+ endPoint.getLatitudeE6()/1000000.0D + "," + endPoint.getLongitudeE6()/1000000.0D
					+ "&daddr=" + startPoint.getLatitudeE6()/1000000.0D + "," + startPoint.getLongitudeE6()/1000000.0D
					+ "&hl=zh&t=m&" + params;
	        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(path)); 
	        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 
	        i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"); 
	        startActivity(i);
		} catch (Exception e) {
			if(endPoint == null || startPoint == null){
				Toast.makeText(this, "缺少起点或终点", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, R.string.not_install_google_map, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public Criteria getCriteria(){
        Criteria c = new Criteria();  
        /*c.setAccuracy(Criteria.ACCURACY_FINE);          //设置查询精度  
        c.setSpeedRequired(false);                      //设置是否要求速度  
        c.setCostAllowed(false);                        //设置是否允许产生费用  
        c.setBearingRequired(false);                    //设置是否需要得到方向  
        c.setAltitudeRequired(false);                   //设置是否需要得到海拔高度  
        c.setPowerRequirement(Criteria.POWER_LOW);      //设置允许的电池消耗级别  
        */
        return c;   
    }

}
